#include <string.h>
#include <stdlib.h>
#include <stdio.h>

//#include <time.h> 
//#include "hi_time.h"  
//#include <hi_types_base.h> 
//#include <hi_wifi_api.h>
//#include <hi_early_debug.h> 

#include "iot_string.h" 
#include "los_base.h"


// 字符串转换 
// https://github.com/ssllab/temper1/blob/722991add4a6a239271e1f029ebe4daaad719496/strreplace.c
char *str_replace(char const * const original, char const * const pattern, char const * const replacement) 
{
    size_t const replen = strlen(replacement);
    size_t const patlen = strlen(pattern);
    size_t const orilen = strlen(original);
  
    size_t patcnt = 0;
    const char * oriptr;
    const char * patloc;
  
    // find how many times the pattern occurs in the original string
    for (oriptr = original; (patloc = strstr(oriptr, pattern)); oriptr = patloc + patlen) {
        patcnt++;
    } 
    
    // allocate memory for the new string
    size_t const retlen = orilen + patcnt * (replen - patlen);
    char * const returned = (char *) malloc( sizeof(char) * (retlen + 1) );

    if (returned != NULL)  {
      // copy the original string, 
      // replacing all the instances of the pattern
        char * retptr = returned;
        for (oriptr = original; (patloc = strstr(oriptr, pattern)); oriptr = patloc + patlen)
        {
            size_t const skplen = patloc - oriptr;
            // copy the section until the occurence of the pattern
            strncpy(retptr, oriptr, skplen);
            retptr += skplen;
            // copy the replacement 
            strncpy(retptr, replacement, replen);
            retptr += replen;
        }
        // copy the rest of the string.
        strcpy(retptr, oriptr);
    }
    return returned;
    
}


// https://www.cnblogs.com/dpf-learn/p/7580568.html 
// 无符号字符串转为 16 进制
void unCharToStr(char *str, unsigned char *unChar, int ucLen)   {  
    int i = 0;  
    for(i = 0; i < ucLen; i++)   {  
        //格式化输str,每unsigned char 转换字符占两位置%x写输%X写输  
        sprintf(str + i * 2, "%02x", unChar[i]);  
    }  
}  
  
// 反转为 字符串
void strTounChar(char *str, unsigned char *unChar)   {  
    int i = strlen(str), j = 0, counter = 0;  
    char c[2];  
    unsigned int bytes[2];  
  
    for (j = 0; j < i; j += 2)   {  
        if(0 == j % 2)   {  
            c[0] = str[j];  
            c[1] = str[j + 1];  
            sscanf(c, "%02x" , &bytes[0]);  
            unChar[counter] = bytes[0];  
            counter++;  
        }  
    }  
    return;  
}  


/* 
//十六进制数转换为十进制数 
long hexToDec(char *source);
 
//返回ch字符在sign数组中的序号
int getIndexOfSigns(char ch);
 
int main()
{
    char *hex = "75BCD15";
 
    printf("16进制数：\t%s\n", hex);
    printf("10进制数：\t%ld\n", hexToDec(hex));
 
    return 0;
}
*/

/* 十六进制数转换为十进制数 */
long hexToDecExt(char *source)
{
    long sum = 0;
    long t = 1;
    int i, len;
 
    len = strlen(source);
    for(i=len-1; i>=0; i--) {
        sum += t * getIndexOfSigns(*(source + i));
        t *= 16;
    }   
    return sum;
}
 
/* 返回ch字符在sign数组中的序号 */
int getIndexOfSigns(char ch)
{
    if(ch >= '0' && ch <= '9') {
        return ch - '0';
    }
    if(ch >= 'A' && ch <='F')  {
        return ch - 'A' + 10;
    }
    if(ch >= 'a' && ch <= 'f') {
        return ch - 'a' + 10;
    }
    return -1;
}



//cl strreplace.c
//gcc strreplace.c
/*
int main(int argc, char const *argv[])
{
	
	char* data=strreplace("java1024android1024cpp1024 from china ","1024","\u6765\u81ea\u4e2d\u56fd");
	printf("%s\n", data);
	data=strreplace("java中文android中文cpp中文 from china ","中文","test");
	printf("%s\n", data);
  

   // ===
    unsigned char src[6] = {0x12, 0x32,0x56,0x78,0x90,0xab};  
    char buffer[20];//维数定义些  
    convertUnCharToStr(buffer, src, 6);    
    printf("%s\n", buffer);  
  
  
    unsigned char dst[6];  
    int len = strlen(buffer);   
    convertStrToUnChar(buffer, dst);  
      
    int i = 0;  
    for(i = 0; i < 6; i++)  
    {  
        printf("%x ", dst[i]);  
    }  
}
*/


uint16_t hex2str(uint16_t hex_byte, uint16_t* str)
{
    uint16_t in_byte = hex_byte;
    static uint16_t m=0;

    if (str == NULL) {
        return -1;  //HI_ERR_FAILURE;
    }
    if (m >= 255) {
        m=0;
    }
    if (((in_byte>>4)&0x0f) <= 9) {
         *(str+m) = ((in_byte>>4)&0x0f) +'0';
    } else {
        *(str+m) = (((in_byte>>4)&0x0f) - 0x20) + 0x57;
    }
    if ((in_byte&0x0f) <= 9) {
        *(str+m+1) = (in_byte&0x0f) + '0';
    } else {
        *(str+m+1) = ((in_byte&0x0f) - 0x20) + 0x57;
    }
    *(str+m+2) = ':';
    m = m+3;

    return 0;
}



/**
 * func  : char_to_hex()
 * desc  : convert ascii to 16 hex
 * input : ascii
 * return: hex
 */
unsigned char char_to_hex2(unsigned char chr)
{
    if((chr>='0')&&(chr<='9'))
        chr = 0x30+(chr-'0');
    else if((chr>='A')&&(chr<='Z'))//capital
        chr = 0x41+(chr - 'A');
    else if((chr>='a')&&(chr<='z'))//little
        chr = 0x61+(chr-'a');
    else
        chr = 0xff;
    return chr;
}

/**
 * func  ：hex_to_char() 
 * desc  ：transform hex to ascii 
 * input ：hex 
 * return：ascii
 */
unsigned char hex_to_char2(unsigned char hex)
{
    if((hex>=0x30)&&(hex<=0x39))
        hex = hex-0x30;
    else if((hex>=0x41)&&(hex<=0x5A)) // capital
        hex = 'A' + (hex - 0x41);
    else if((hex>=0x61)&&(hex<=0x7A)) // little case
        hex = 'a' + (hex - 0x61);
    else 
        hex = 0xff;
    return hex;
}



// https://blog.csdn.net/wangqingchuan92/article/details/103816046
// 字符串化成十六进制数组
int StringToBuff(char *str,unsigned char *OutputBuff)
{
	char *p = NULL;
	char High = 0;
	char Low = 0;
	//int i = 0;
	int Len = 0;
	int count = 0;
	
	p = str;
	Len = strlen(p);

	while(count < (Len/2))
    {
        High = ((*p > '9') && ((*p <= 'F') || (*p <= 'f')))?*p - 48 - 7 : *p - 48;
		Low = (*(++ p) > '9' && ((*p <= 'F') || (*p <= 'f')))? *p - 48 - 7 : *p - 48;
        OutputBuff[count] = ((High & 0x0f) << 4 | (Low & 0x0f));
        p ++;
        count ++;
    }
	//判断字符串长度是否为奇数
	if(0 != Len%2)
	{
		OutputBuff[count++] = (((*p >'9')&&(*p<='F'))||(*p<='f'))?*p-48-7:*p-48;
	}
	
	return Len/2 + Len%2;
}

// 十六进制数组转化成字符串
int ArrayToStr(unsigned char *Buff, unsigned int BuffLen, char *OutputStr)
{
	unsigned int i = 0;
	char TempBuff[128] = {0};
	char strBuff[256] = {0};
	
	for(i = 0; i<BuffLen;i++)
	{
		sprintf(TempBuff,"%02x",Buff[i]);//以十六进制格式输出到TempBuff，宽度为2
		strncat(strBuff,TempBuff,BuffLen*2);//将TempBuff追加到strBuff结尾
	}
	strncpy(OutputStr, strBuff, BuffLen*2); //将strBuff复制到OutputStr
	return BuffLen*2;
}

// 长整数转为 4 字节的 buff 数组
int IntToBuff4(long data, unsigned char *buff)
{
	char str1[10] = {0};
	sprintf(str1,"%X",data);
	int len = strlen(str1); 
	//printf("str1=%s, len=%d\r\n",str1, len);
	
	char prefix[10] = {0};
	for(int i=0; i< 8- len; i++){
        prefix[i] = '0';
    }
	//printf("%s\n", prefix);
	
	char str2[10] = {0};
    sprintf(str2, "%s%s", prefix, str1);
    //printf("str2=%s, len=%d\r\n", str2, strlen(str2)); 
	
	return StringToBuff(str2, buff); 
}

// 长整数转为 2 字节的 buff 数组
int IntToBuff2(long data, unsigned char *buff)
{
	char str1[10] = {0};
	sprintf(str1,"%X",data);
	int len = strlen(str1); 
	//printf("str1=%s, len=%d\r\n",str1, len);
	
	char prefix[10] = {0};
	for(int i=0; i< 4- len; i++){
        prefix[i] = '0';
    }
	//printf("%s\n", prefix);
	
	char str2[10] = {0};
    sprintf(str2, "%s%s", prefix, str1);
    //printf("str2=%s, len=%d\r\n", str2, strlen(str2)); 
	
	return StringToBuff(str2, buff); 
}

/* 举例
unsigned char ArrayHex[16] = {0x1a, 0x2b, 0x3c, 0x4d, 0x5e, 0x6f, 0x7b, 0x8d, 0x9e, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16};

char *strCom = "1a2b3c4d5e6f7a8b9c1011121314";
 
int main(int argc, const char *argv)
{
    int i= 0;
    int outlen = 0;
    char str[33] = {0};
    unsigned char out[33] = {0};
    
    ArrayToStr(ArrayHex, 16, str);   
    printf("after ArrayToStr :%s\n",str);
    
    outlen = StringToBuff(strCom, out);
    printf("after StringToBuff: ");
    for(i= 0; i< outlen; i++)
    {
        printf("%02X ", out[i]);
    } 
	printf("\n\n"); 
	
	unsigned char *out2;
	outlen = IntToBuff4(114370, out2);
	for(i= 0; i< outlen; i++)
    {
        printf("%02X ", out2[i]);
    } 
	printf("\noutlen=%d\n", outlen);

    return 0;
}
*/




//typedef unsigned char   uint8_t;

const unsigned char Num2CharTable[] = "0123456789ABCDEF";

// 16进制转字符串
void HexArrayToStr(unsigned char *hexarray, int length, unsigned char *string)
{
    int i = 0;
    while(i < length)
    {
        *(string++) = Num2CharTable[(hexarray[i] >> 4) & 0x0f];
        *(string++) = Num2CharTable[hexarray[i] & 0x0f];
        i++;
    }
    *string = 0x0;
}

// 16进制转 整数
long int HexArrayToDec(unsigned char *hexarray, int len)
{
    unsigned char dst[50];
    HexArrayToStr(hexarray, len, dst);

    int t;
    long sum=0;
    for(int i=0;dst[i];i++){
        if(dst[i]<='9')
            t=dst[i]-'0';
        else
            t=dst[i]-'A'+10;
        sum=sum*16+t;
    }
    return sum;
}



// 截取字符c之前(含c)的子串，返回dest
void jsonTrimEnd(char *src, int c, char *dest){
	// strrchr() 函数用于查找某字符在字符串中最后一次出现的位置
	char *p = strrchr(src, c);  
    strncpy(dest, src, strlen(src) - strlen(p+1));
}

/*
int main(){
    uint8_t dst[50];
    uint8_t data[2]={0x01,0x04};
    long int res;
    res = HexArrayToDec(data,2);
    printf("%ld\n",res);
    return 0;
}
*/